﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SLogo.Helper
{
    /// <summary>
    /// 对字符串提供帮助的类
    /// </summary>
    class StringHelper
    {
        /// <summary>
        /// 判断是否为合法的标识符
        /// </summary>
        /// <param name="token">标识符字符串</param>
        /// <returns>若是则为真</returns>
        public static bool IsToken(String token)
        {
            if(token[0] >= '1' && token[0] <= '9')
            {
                return false;
            }
            return token.All(t => t == '_' || (t >= '1' && t <= '9') || (t >= 'a' && t <= 'z'));
        }
        /// <summary>
        /// 字符串转为Byte[]
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>byte数组</returns>
        public static byte[] ToBytes(String s)
        {
            byte[] res = new byte[s.Length];
            for(int i = s.Length - 1; i >= 0  ; i--)
            {
                res[i] = (byte) s[i];
            }
            return res;
        }
        /// <summary>
        /// 将Utf8编码转换为Ansi编码
        /// </summary>
        /// <param name="utf8String">UTF8字符串</param>
        /// <returns>ANSI字符串</returns>
        public static String Utf8ToAnsi(String utf8String)
        {
            return Encoding.UTF8.GetString(Encoding.Convert(Encoding.UTF8, Encoding.Default,
                                                         Encoding.UTF8.GetBytes(utf8String)));
        }
        /// <summary>
        /// 将Ansi编码转换为Utf8编码
        /// </summary>
        /// <param name="ansiString">Ansi编码</param>
        /// <returns>Utf8编码</returns>
        public static String AnsiToUtf8(String ansiString)
        {
            return Encoding.UTF8.GetString(Encoding.Convert(Encoding.Default, Encoding.UTF8,
                                                         Encoding.Default.GetBytes(ansiString)));
        }
    }
}
